iT邦幫忙

2024 iThome 鐵人賽

DAY 10
0

來數一下行程數量吧~

#include <stdio.h>
#include <unistd.h>

int main()
{
	int i = 0;

    for ( i = 0; i < 4; i++)
	    fork();
	return 0;
}

圖3.31 產生了多少行程?

fork() 函數會創建一個新的行程。每次調用 fork(),當前行程會被複製一個子行程。
初始時有一個行程(父行程)。
在第一次迴圈時,調用 fork() 會產生 2 個行程(1 個父行程 + 1 個子行程)。
在第二次迴圈時,每個現有的行程(2 個)都會再次調用 fork(),這將產生 4 個行程(2 個現有行程各自再創建 1 個子行程)。
在第三次迴圈時,每個現有的行程(4 個)再次調用 fork(),這將產生 8 個行程。
在第四次迴圈時,每個現有的行程(8 個)再次調用 fork(),這將產生 16 個行程。

改一下原有的 fork-question-2.c 程式碼,也可以得出有 16 個行程這個答案。

/**
 * Solution to exercise 3.31
 *
 * The answer is easily determined by counting 
 * the number of unique processes which are output
 * by the call to getpid() - which is 16 unique processes.
 */

#include <stdio.h>

int main()
{
	printf("%d\n",getpid());
	fork();
	printf("%d\n",getpid());
	

	fork();
	printf("%d\n",getpid());

	fork();
	printf("%d\n",getpid());
    
    fork();
	printf("%d\n",getpid());

	return 0;
}

Terminal
編譯並執行

gcc -o fork-question-2 fork-question-2.c
./fork-question-2

結果(為了避免算到眼花,我只保留最後一個 printf ):
https://ithelp.ithome.com.tw/upload/images/20240924/20168766yDWFy6RjrZ.png

參考:greggagne/OSC9e/ch3/fork-question-2.c


上一篇
ch3.6.3.2-命名管道(Name Pipes)
下一篇
ch4-多執行緒
系列文
十年後重讀作業系統恐龍本12
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言